﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TimerMaster : MonoBehaviour {
    public static TimerMaster _;
    public HashSet<Timer> Timers = new HashSet<Timer>();
    public int TimerNums = 0;

    public TimerMaster()
    {
        _ = this;
    }

    public void Start()
    {
        
    }

    public void FixedUpdate()
    {
        Timers.RemoveWhere((c) =>
        {
            c.TimeOut((int)(Time.deltaTime * 1000));
            return c.needDestroy();
        });
        TimerNums = Timers.Count;
    }
    public delegate void work();

    /// <summary>
    /// 按照指定的周期（以毫秒计）来调用函数
    /// </summary>
    /// <param name="ms">间隔</param>
    /// <returns></returns>
    public static Timer setInterval(work w,int ms)
    {
        var res = new Timer(w, ms, -1);
        _.Timers.Add(res);
        return res;
    }

    /// <summary>
    /// 按照指定的周期（以毫秒计）来调用函数
    /// </summary>
    /// <param name="ms">间隔</param>
    /// <param name="time">次数</param>
    /// <returns></returns>
    public static Timer setInterval(work w, int ms,int time)
    {
        var res = new Timer(w, ms, time);
        _.Timers.Add(res);
        return res;
    }

    /// <summary>
    /// 在指定的毫秒数后调用函数
    /// </summary>
    /// <param name="ms">间隔</param>
    /// <returns></returns>
    public static Timer setTimeout(work w, int ms)
    {
        var res = new Timer(w, ms, 1);
        _.Timers.Add(res);
        return res;
    }

    public static bool clearInterval(Timer t)
    {
        return _.Timers.Remove(t);
    }

    public class Timer
    {
        int ms;
        int nowTime;
        work w;
        int time = 1;
        public Timer(work w, int ms,int time)
        {
            this.ms = ms;
            this.nowTime = ms;
            this.w = w;
            this.time = time;
        }
        public void TimeOut(int ms)
        {
            nowTime -= ms;
            if (nowTime <= 0)
            {
                time--;
                nowTime += this.ms;
                w();
            }
        }
        public bool needDestroy()
        {
            return time <= 0;
        }
    }
}